<template>
  <view :class="{'schedule-create-container': !isLandscape}">
	<template v-if="!isLandscape">
		<!-- 页面标题 -->
		<view class="page-header">
		  <text class="page-title">创建赛程</text>
		  <text class="page-subtitle">为赛事创建新的赛程安排</text>
		</view>
		
		<!-- 创建表单 -->
		<view class="form-section">
		  <view class="form-card">
			<view class="form-item">
			  <text class="form-label">赛程名称 *</text>
			  <input 
				class="form-input" 
				v-model="formData.name" 
				placeholder="请输入赛程名称"
				maxlength="100"
			  />
			</view>
			
			<view class="form-item">
			  <text class="form-label">关联赛事 *</text>
			  <picker 
				class="form-picker" 
				:value="matchIndex" 
				:range="matchOptions" 
				@change="onMatchChange"
			  >
				<text class="picker-text">{{ matchOptions[matchIndex] || '请选择关联赛事' }}</text>
			  </picker>
			</view>
			
			<view class="form-item">
			  <text class="form-label">赛程模型 *</text>
			  <picker 
				class="form-picker" 
				:value="modelIndex" 
				:range="modelOptions" 
				@change="onModelChange"
			  >
				<text class="picker-text">{{ modelOptions[modelIndex] || '请选择赛程模型' }}</text>
			  </picker>
			</view>
			
			<view class="form-item">
			  <text class="form-label">赛程开始时间 *</text>
			  <picker 
				class="form-picker" 
				mode="date" 
				:value="scheduleStartDate" 
				@change="onScheduleStartDateChange"
			  >
				<text class="picker-text">{{ scheduleStartDate || '请选择赛程开始日期' }}</text>
			  </picker>
			</view>
			
			<view class="form-item">
			  <text class="form-label">赛程结束时间 *</text>
			  <picker 
				class="form-picker" 
				mode="date" 
				:value="scheduleEndDate" 
				@change="onScheduleEndDateChange"
			  >
				<text class="picker-text">{{ scheduleEndDate || '请选择赛程结束日期' }}</text>
			  </picker>
			</view>
			
			<view class="form-item">
			  <text class="form-label">报名开始时间 *</text>
			  <picker 
				class="form-picker" 
				mode="date" 
				:value="regStartDate" 
				@change="onRegStartDateChange"
			  >
				<text class="picker-text">{{ regStartDate || '请选择报名开始日期' }}</text>
			  </picker>
			</view>
			
			<view class="form-item">
			  <text class="form-label">报名结束时间 *</text>
			  <picker 
				class="form-picker" 
				mode="date" 
				:value="regEndDate" 
				@change="onRegEndDateChange"
			  >
				<text class="picker-text">{{ regEndDate || '请选择报名结束日期' }}</text>
			  </picker>
			</view>
			
			<view class="form-item">
			  <text class="form-label">赛程状态</text>
			  <picker 
				class="form-picker" 
				:value="statusIndex" 
				:range="statusOptions" 
				@change="onStatusChange"
			  >
				<text class="picker-text">{{ statusOptions[statusIndex] }}</text>
			  </picker>
			</view>
			
			<view class="form-buttons">
			  <button class="submit-btn" @click="createSchedule" :disabled="loading">
				{{ loading ? '创建中...' : '创建赛程' }}
			  </button>
			  <button class="cancel-btn" @click="goBack">取消</button>
			</view>
		  </view>
		</view>
	</template>
	<LandscapePage v-else :go-back="goBack" :create-schedule="createSchedule" :loading="loading">
		<!-- 创建表单 -->
		<view class="form-section">
			<view class="form-item">
			  <text class="form-label required">赛程名称</text>
			  <input 
				class="form-input" 
				v-model="formData.name" 
				placeholder="请输入赛程名称"
				maxlength="100"
			  />
			</view>
			
			<view class="form-item">
			  <text class="form-label required">关联赛事</text>
			  <picker 
				class="form-picker" 
				:value="matchIndex" 
				:range="matchOptions" 
				@change="onMatchChange"
			  >
				<text class="picker-text" :class="{placeholder: !matchOptions[matchIndex] }">{{ matchOptions[matchIndex] || '请选择关联赛事' }}</text>
			  </picker>
			</view>
			
			<view class="form-item">
			  <text class="form-label required">赛程模型</text>
			  <picker 
				class="form-picker" 
				:value="modelIndex" 
				:range="modelOptions" 
				@change="onModelChange"
			  >
				<text class="picker-text" :class="{placeholder: !modelOptions[modelIndex] }">{{ modelOptions[modelIndex] || '请选择赛程模型' }}</text>
			  </picker>
			</view>
			
			<view class="form-item">
			  <text class="form-label required">赛程开始时间</text>
			  <picker 
				class="form-picker" 
				mode="date" 
				:value="scheduleStartDate" 
				@change="onScheduleStartDateChange"
			  >
				<text class="picker-text" :class="{placeholder: !scheduleStartDate }">{{ scheduleStartDate || '请选择赛程开始日期' }}</text>
			  </picker>
			</view>
			
			<view class="form-item">
			  <text class="form-label required">赛程结束时间</text>
			  <picker 
				class="form-picker" 
				mode="date" 
				:value="scheduleEndDate" 
				@change="onScheduleEndDateChange"
			  >
				<text class="picker-text" :class="{placeholder: !scheduleEndDate }">{{ scheduleEndDate || '请选择赛程结束日期' }}</text>
			  </picker>
			</view>
			
			<view class="form-item">
			  <text class="form-label required">报名开始时间</text>
			  <picker 
				class="form-picker" 
				mode="date" 
				:value="regStartDate" 
				@change="onRegStartDateChange"
			  >
				<text class="picker-text" :class="{placeholder: !regStartDate }">{{ regStartDate || '请选择报名开始日期' }}</text>
			  </picker>
			</view>
			
			<view class="form-item">
			  <text class="form-label required">报名结束时间</text>
			  <picker 
				class="form-picker" 
				mode="date" 
				:value="regEndDate" 
				@change="onRegEndDateChange"
			  >
				<text class="picker-text" :class="{placeholder: !regEndDate }">{{ regEndDate || '请选择报名结束日期' }}</text>
			  </picker>
			</view>
			
			<view class="form-item">
			  <text class="form-label">赛程状态</text>
			  <picker 
				class="form-picker" 
				:value="statusIndex" 
				:range="statusOptions" 
				@change="onStatusChange"
			  >
				<text class="picker-text">{{ statusOptions[statusIndex] }}</text>
			  </picker>
			</view>
		</view>
	</LandscapePage>
    
    <!-- 加载状态 -->
    <view class="loading-overlay" v-if="loading">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">创建中...</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { MatchScheduleAPI, MatchAPI, MatchScheduleModelAPI } from '@/api/battle.js'
import LandscapePage from '@/views/landscape/schedule-create.vue'
import useIsLandscape from '@/composables/useIsLandscape.js'

const { isLandscape } = useIsLandscape()

// 响应式数据
const loading = ref(false)
const matchIndex = ref(0)
const modelIndex = ref(0)
const statusIndex = ref(0)
const scheduleStartDate = ref('')
const scheduleEndDate = ref('')
const regStartDate = ref('')
const regEndDate = ref('')

// URL参数
const urlMatchId = ref('')
const urlMatchName = ref('')

// 表单数据
const formData = ref({
  matchId: '',
  matchScheduleModelId: '',
  name: '',
  startTime: 0,
  endTime: 0,
  regStartTime: 0,
  regEndTime: 0,
  status: 0
})

// 选项数据
const matchOptions = ref([])
const modelOptions = ref([])
const matchList = ref([])
const modelList = ref([])

// 状态选项
const statusOptions = [
  '待发布', '发布中', '发布完成', '报名中', '报名结束', 
  '赛程准备中', '赛程准备完成', '赛程进行中', '赛程核算中', 
  '赛程完成', '赛程取消', '赛程暂停'
]

// 处理URL参数
onLoad((options) => {
  if (options.matchId) {
    urlMatchId.value = options.matchId
  }
  if (options.matchName) {
    urlMatchName.value = decodeURIComponent(options.matchName)
  }
})

// 赛事选择变化
const onMatchChange = (e) => {
  const index = e.detail.value
  matchIndex.value = index
  if (matchList.value[index]) {
    formData.value.matchId = matchList.value[index].id
  }
}

// 模型选择变化
const onModelChange = (e) => {
  const index = e.detail.value
  modelIndex.value = index
  if (modelList.value[index]) {
    formData.value.matchScheduleModelId = modelList.value[index].id
  }
}

// 状态选择变化
const onStatusChange = (e) => {
  const index = e.detail.value
  statusIndex.value = index
  formData.value.status = index
}

// 赛程开始日期变化
const onScheduleStartDateChange = (e) => {
  scheduleStartDate.value = e.detail.value
  formData.value.startTime = new Date(e.detail.value).getTime()
}

// 赛程结束日期变化
const onScheduleEndDateChange = (e) => {
  scheduleEndDate.value = e.detail.value
  formData.value.endTime = new Date(e.detail.value + ' 23:59:59').getTime()
}

// 报名开始日期变化
const onRegStartDateChange = (e) => {
  regStartDate.value = e.detail.value
  formData.value.regStartTime = new Date(e.detail.value).getTime()
}

// 报名结束日期变化
const onRegEndDateChange = (e) => {
  regEndDate.value = e.detail.value
  formData.value.regEndTime = new Date(e.detail.value + ' 23:59:59').getTime()
}

// 加载赛事列表
const loadMatchList = async () => {
  try {
    const result = await MatchAPI.page({
      pageNum: 0,
      pageSize: 100
    })
    
    if (result.code === 0 && result.data) {
      matchList.value = result.data
      matchOptions.value = result.data.map(match => match.name)
      
      // 如果URL中有指定的matchId，则预选该赛事
      if (urlMatchId.value) {
        const targetIndex = result.data.findIndex(match => match.id === urlMatchId.value)
        if (targetIndex !== -1) {
          matchIndex.value = targetIndex
          formData.value.matchId = result.data[targetIndex].id
        } else {
          // 如果找不到指定的赛事，选择第一个
          formData.value.matchId = result.data[0].id
        }
      } else if (result.data.length > 0) {
        formData.value.matchId = result.data[0].id
      }
    }
  } catch (error) {
    console.error('加载赛事列表失败:', error)
  }
}

// 加载模型列表
const loadModelList = async () => {
  try {
    const result = await MatchScheduleModelAPI.page({
      pageNum: 0,
      pageSize: 100
    })
    
    if (result.code === 0 && result.data) {
      const list = result.data.list || result.data || []
      modelList.value = list
      modelOptions.value = list.map(model => 
        `房间类型:${getRoomTypeText(model.roomType)} | 获胜模式:${getWinModelText(model.matchWinModel)}`
      )
      
      if (list.length > 0) {
        formData.value.matchScheduleModelId = list[0].id
      }
    }
  } catch (error) {
    console.error('加载模型列表失败:', error)
  }
}

// 获取房间类型文本
const getRoomTypeText = (type) => {
  const types = ['N对N 2组', '单人 1组', '1对1 2组', '2对2 2组', '单人多组 N组', '多人多组 N组']
  return types[type] || '未知'
}

// 获取获胜模式文本
const getWinModelText = (type) => {
  const types = [
    '一回合 抢1分', '三回合 抢2分', '五回合 抢3分', '高分', 'BO3', 
    'AO5', 'BAO5', '时间短', '步数短', '距离长', '五局（抢3） 五回合（抢3）'
  ]
  return types[type - 1] || '未知'
}

// 创建赛程
const createSchedule = async () => {
  // 表单验证
  if (!formData.value.name.trim()) {
    uni.showToast({
      title: '请输入赛程名称',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.matchId) {
    uni.showToast({
      title: '请选择关联赛事',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.matchScheduleModelId) {
    uni.showToast({
      title: '请选择赛程模型',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.startTime) {
    uni.showToast({
      title: '请选择赛程开始时间',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.endTime) {
    uni.showToast({
      title: '请选择赛程结束时间',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.regStartTime) {
    uni.showToast({
      title: '请选择报名开始时间',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.regEndTime) {
    uni.showToast({
      title: '请选择报名结束时间',
      icon: 'none'
    })
    return
  }
  
  // 时间逻辑验证
  if (formData.value.regEndTime >= formData.value.startTime) {
    uni.showToast({
      title: '报名结束时间必须早于赛程开始时间',
      icon: 'none'
    })
    return
  }
  
  if (formData.value.endTime <= formData.value.startTime) {
    uni.showToast({
      title: '赛程结束时间必须晚于开始时间',
      icon: 'none'
    })
    return
  }
  
  loading.value = true
  try {
    const result = await MatchScheduleAPI.create(formData.value)
    
    console.log('创建赛程API返回结果:', result)
    
    if (result.code === 0) {
      uni.showToast({
        title: '赛程创建成功',
        icon: 'success'
      })
      
      // 延迟返回上一页
      setTimeout(() => {
        goBack()
      }, 1500)
    } else {
      throw new Error(result.msg || '创建失败')
    }
  } catch (error) {
    console.error('创建赛程失败:', error)
    uni.showToast({
      title: error.message || '创建失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 页面加载时获取数据
onMounted(() => {
  loadMatchList()
  loadModelList()
})
</script>

<style lang="scss" scoped>
.schedule-create-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx;
}

.page-header {
  text-align: center;
  margin-bottom: 60rpx;
  
  .page-title {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 20rpx;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
  }
  
  .page-subtitle {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.form-section {
  .form-card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    padding: 40rpx;
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
    
    .form-item {
      margin-bottom: 30rpx;
      
      .form-label {
        display: block;
        font-size: 28rpx;
        color: #333;
        margin-bottom: 15rpx;
        font-weight: bold;
      }
      
      .form-input {
        width: 100%;
        height: 80rpx;
        border: 2rpx solid #eee;
        border-radius: 12rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
        background: #fff;
        box-sizing: border-box;
      }
      
      .form-picker {
        width: 100%;
        height: 80rpx;
        border: 2rpx solid #eee;
        border-radius: 12rpx;
        padding: 0 20rpx;
        background: #fff;
        display: flex;
        align-items: center;
        box-sizing: border-box;
        
        .picker-text {
          font-size: 28rpx;
          color: #333;
        }
      }
    }
    
    .form-buttons {
      display: flex;
      gap: 20rpx;
      margin-top: 40rpx;
      
      .submit-btn,
      .cancel-btn {
        flex: 1;
        height: 80rpx;
        border: none;
        border-radius: 12rpx;
        font-size: 28rpx;
        font-weight: bold;
        
        &.submit-btn {
          background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
          color: #fff;
          
          &:disabled {
            opacity: 0.6;
          }
        }
        
        &.cancel-btn {
          background: #f8f9fa;
          color: #666;
          border: 2rpx solid #eee;
        }
      }
    }
  }
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .loading-content {
    background: #fff;
    border-radius: 20rpx;
    padding: 60rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .loading-spinner {
      width: 60rpx;
      height: 60rpx;
      border: 4rpx solid #f3f3f3;
      border-top: 4rpx solid #667eea;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 20rpx;
    }
    
    .loading-text {
      font-size: 28rpx;
      color: #666;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 